package com.etcfg.etlaunch.ui;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;

import com.etcfg.etlaunch.ETServer;

public class ServerListModel extends AbstractTableModel implements
		PropertyChangeListener {

	private List<ETServer> servers = new ArrayList<ETServer>();

	public List<ETServer> getServers() {
		return servers;
	}

	public void addServer(ETServer etServer) {
		servers.add(etServer);
		etServer.addPropertyChangeListener("serverStatus", this);
		fireTableRowsInserted(servers.size() - 1, servers.size() - 1);

	}

	public void removeServer(ETServer etServer) {
		int indexOf = servers.indexOf(etServer);
		servers.remove(indexOf);
		etServer.removePropertyChangeListener("serverStatus", this);
		fireTableRowsDeleted(indexOf, indexOf);

	}

	@Override
	public int getColumnCount() {
		return 1;
	}

	@Override
	public int getRowCount() {
		return servers.size();
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		return servers.get(rowIndex);
	}

	@Override
	public String getColumnName(int column) {
		if (column == 0) {
			return "Servers";
		}
		return "Column " + column;
	}

	@Override
	public void propertyChange(final PropertyChangeEvent evt) {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				ETServer etServer = (ETServer) evt.getSource();
				int indexOf = servers.indexOf(etServer);
				if (indexOf > -1) {
					fireTableRowsUpdated(indexOf, indexOf);
				}

			}
		});

	}

}
